<script setup lang="ts">
import { CircleClose } from '@element-plus/icons-vue';
import { ElIcon, ElInput, ElUpload } from 'element-plus';
import { ref, toRefs } from 'vue';

import { IForm } from '@/types';

const props = defineProps<{
  config: IForm & { type: 'singleUpload' };
  value?: File;
}>();
const emits = defineEmits<{
  (event: 'update:value', value: File | undefined): void;
  (event: 'change', value: any): void;
}>();
const { config } = toRefs(props);
const removeFile = () => {
  fileList.value = [];
  emits('update:value', undefined);
};
const fileList = ref([]);
const setFile = (file?: File) => {
  emits('update:value', file);
};
</script>

<template>
  <el-input class="form-upload-single" readonly :placeholder="'请选择' + config.label" :model-value="value?.name" v-bind="config.option">
    <template #suffix>
      <el-icon v-if="value?.name" style="cursor: pointer" @click="removeFile"><CircleClose /></el-icon>
    </template>
    <template #append>
      <el-upload
        :limit="1"
        :auto-upload="false"
        :show-file-list="false"
        @click="removeFile"
        :onChange="(fileList) => setFile(fileList?.raw)"
        v-model:fileList="fileList"
        v-bind="config.uploadOption"
      >
        <div>选择文件</div>
      </el-upload>
    </template>
  </el-input>
</template>

<style scoped lang="scss"></style>
